package com.robot.ad.service;

import com.robot.ad.dao.AdDao;
import com.robot.ad.pojo.Ad;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * ad服务层
 *
 * @author wuyunbin
 */
@Service
public class AdService {

    @Autowired
    private AdDao adDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<Ad> findAll() {
        return adDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<Ad> findSearch(Map whereMap, int page, int size) {
        Specification<Ad> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return adDao.findAll(specification, pageRequest);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<Ad> findSearch(Map whereMap) {
        Specification<Ad> specification = createSpecification(whereMap);
        return adDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public Ad findById(String id) {
        return adDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param ad
     */
    public void add(Ad ad) {
        //雪花分布式ID生成器
        //雪花分布式ID生成器
        ad.setId(idWorker.nextId() + "");
        LocalDateTime now = LocalDateTime.now();
        ad.setCreatedAt(now);
        ad.setUpdatedAt(now);
        adDao.save(ad);
    }

    /**
     * 修改
     *
     * @param ad
     */
    public void update(Ad ad) {
        ad.setUpdatedAt(LocalDateTime.now());
        adDao.save(ad);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        adDao.deleteById(id);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Ad> createSpecification(Map searchMap) {
        return new Specification<Ad>() {
            @Override
            public Predicate toPredicate(Root<Ad> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 广告id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 广告标题
                String title = "title";
                if (searchMap.get(title) != null && !"".equals(searchMap.get(title))) {
                    predicateList.add(cb.like(root.get(title).as(String.class), "%" + (String) searchMap.get(title) + "%"));
                }
                // 广告类型 0-图片 1-视频
                String type = "type";
                if (searchMap.get(type) != null && !"".equals(searchMap.get(type))) {
                    predicateList.add(cb.like(root.get(type).as(String.class), "%" + (String) searchMap.get(type) + "%"));
                }
                // 广告位置
                String position = "position";
                if (searchMap.get(position) != null && !"".equals(searchMap.get(position))) {
                    predicateList.add(cb.like(root.get(position).as(String.class), "%" + (String) searchMap.get(position) + "%"));
                }
                // 广告指向url
                String url = "url";
                if (searchMap.get(url) != null && !"".equals(searchMap.get(url))) {
                    predicateList.add(cb.like(root.get(url).as(String.class), "%" + (String) searchMap.get(url) + "%"));
                }
                // 0-禁用 1-启用
                String status = "status";
                if (searchMap.get(status) != null && !"".equals(searchMap.get(status))) {
                    predicateList.add(cb.like(root.get(status).as(String.class), "%" + (String) searchMap.get(status) + "%"));
                }

                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(LocalDateTime.class)));
                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * 根据position和status查找广告列表
     *
     * @param position
     * @param status
     * @return
     */
    public List<Ad> findTop2ByPositionAndStatusAndDeletedAtIsNullOrderBySortDesc(String position, String status) {
        return adDao.findTop2ByPositionAndStatusAndDeletedAtIsNullOrderBySortDesc(position, status);
    }

    /**
     * 根据position和status和areaId查找num个广告列表
     *
     * @param position
     * @param status
     * @param areaId
     * @param num
     * @return
     */
    public List<Ad> findTop2ByPositionAndStatusAndAreaListLikeAndDeletedAtIsNullOrderBySortDesc(String position, String status, String areaId, int num) {
        return adDao.findTop2ByPositionAndStatusAndAreaListLikeAndDeletedAtIsNullOrderBySortDesc(position, status, areaId, num);
    }
}
